package com.demo.springbooot_demo.config;


import com.demo.springbooot_demo.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import com.demo.springbooot_demo.utils.CustomBCryptPasswordEncoder;


import java.io.PrintWriter;


/**
 * security 配置
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    /**
     * 密码 加解密
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        //默认php Yii框架的密码加密一致
        return new CustomBCryptPasswordEncoder(13,"$2y$");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers("/user/login").anonymous()
            .anyRequest().authenticated()
            .and()
            .exceptionHandling().authenticationEntryPoint(
                    //处理登陆异常
                    (request, response, authException) -> {
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");
                    response.setStatus(401);
                    PrintWriter writer = response.getWriter();
                    writer.write("{\"code\":401,\"msg\":\"" + authException.getMessage()  + "\",\"data\":null}");
                    writer.flush();
            }).accessDeniedHandler(
                    //处理授权异常
                    (request, response, accessDeniedException) -> {
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");
                    response.setStatus(403);
                    PrintWriter writer = response.getWriter();
                    writer.write("{\"code\":403,\"msg\":\"" + accessDeniedException.getMessage()  + "\",\"data\":null}");
                    writer.flush();
            });
        //把过滤器指定给异常处理过滤器位置之后
        http.addFilterAfter(jwtAuthenticationTokenFilter, ExceptionTranslationFilter.class);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}
